package com.zys.sac.core.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 响应结果统一处理工具类
 *
 * Created by zhongjunkai on 2022/3/8.
 */
public class ServletResponseUtils {

    public static void render(HttpServletResponse response, Result data) throws IOException {
        // 允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        response.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
        // 设置json响应格式
        response.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        ServletOutputStream writer = response.getOutputStream();
        writer.write(objectMapper.writeValueAsBytes(data));
        writer.flush();
        writer.close();
    }

    public static Result result(String code, String msg, String token) {
        Result result = new Result();
        result.setCode(code);
        result.setMessage(msg);
        result.setToken(token);
        return result;
    }

    public static Result result(String code, String msg, Object data) {
        Result result = new Result();
        result.setCode(code);
        result.setMessage(msg);
        result.setData(data);
        return result;
    }

    public static Result result(String code, String msg) {
        return result(code, msg, null);
    }

    public static Result result(String msg) {
        return result(null, msg);
    }

    public static class Result {
        private String code;

        private String message;

        private String token;

        private Object data;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }
    }
}
